package net.borderwars.util;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author ehubbard
 *         Date: Aug 10, 2005
 *         Time: 4:28:40 PM
 */
public class MenuItemAdapter implements ActionListener {

    private String method;
    private Object o;

    public MenuItemAdapter (String method, Object o) {
        this.method = method;
        this.o = o;
    }

    public static void addMenuItem (JPopupMenu menu, String menuText, String method, Object o) {
        JMenuItem mi = new JMenuItem (menuText);
        mi.addActionListener (new MenuItemAdapter (method, o));
        menu.add (mi);
    }

    public void actionPerformed (ActionEvent e) {

        Class types[] = new Class[1];
        types[0] = e.getClass ();

        Object parms[] = new Object[1];
        parms[0] = e;

        try {
            Method m = o.getClass ().getMethod (method, types);
            m.invoke (o, parms);
        }
        catch (NoSuchMethodException e1) {
            e1.printStackTrace ();
        }
        catch (IllegalAccessException e1) {
            e1.printStackTrace ();
        }
        catch (InvocationTargetException e1) {
            e1.getCause ().printStackTrace ();
        }
    }
}
